package com.example.mqtt.service.impl;

import com.example.mqtt.service.MqttService;
import org.eclipse.paho.client.mqttv3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MqttServiceImpl implements MqttService {
    private static final Logger logger = LoggerFactory.getLogger(MqttServiceImpl.class);
    private final MqttClient mqttClient;
    private IMqttMessageListener messageListener;

    @Autowired
    public MqttServiceImpl(MqttClient mqttClient) {
        this.mqttClient = mqttClient;
        // 设置默认消息监听器
        this.mqttClient.setCallback(new MqttCallbackExtended() {
            @Override
            public void connectComplete(boolean reconnect, String serverURI) {
                logger.info("MQTT连接成功: {}", serverURI);
            }

            @Override
            public void connectionLost(Throwable cause) {
                logger.error("MQTT连接丢失", cause);
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                if (messageListener != null) {
                    messageListener.messageArrived(topic, message);
                }
                logger.info("收到消息 - Topic: {}, Payload: {}", topic, new String(message.getPayload()));
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
                logger.debug("消息投递完成: {}", token.getMessageId());
            }
        });
    }

    @Override
    public void publish(String topic, String message) throws MqttException {
        MqttMessage mqttMessage = new MqttMessage(message.getBytes());
        mqttMessage.setQos(1);
        mqttClient.publish(topic, mqttMessage);
        logger.info("已发送消息到 {} : {}", topic, message);
    }

    @Override
    public void subscribe(String topic) throws MqttException {
        mqttClient.subscribe(topic, 1); // QoS级别1
        logger.info("已订阅主题: {}", topic);
    }

    @Override
    public void setMessageArrivedListener(IMqttMessageListener listener) {
        this.messageListener = listener;
    }
}
